<template>
  <div class="auth-page">
    <!-- 背景装饰 -->
    <div class="auth-background">
      <div class="bg-decoration"></div>
    </div>
    
    <!-- 主内容区域 -->
    <div class="auth-container">
      <!-- 页面标题 -->
      <div class="auth-header">
        <h1 class="auth-title">欢迎使用硅谷租房</h1>
        <p class="auth-subtitle">找到您的理想住所</p>
      </div>
      
      <!-- 登录注册切换 -->
      <div class="auth-tabs">
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'login' }"
          @click="switchTab('login')"
        >
          登录
        </div>
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'register' }"
          @click="switchTab('register')"
        >
          注册
        </div>
      </div>
      
      <!-- 表单容器 -->
      <div class="form-container">
        <!-- 登录表单 -->
        <div 
          class="form-wrapper" 
          :class="{ active: activeTab === 'login' }"
          v-show="activeTab === 'login'"
        >
          <form @submit.prevent="handleLogin" class="auth-form">
            <div class="form-group">
              <label class="form-label">手机号</label>
              <input 
                v-model="loginForm.phone"
                type="tel" 
                class="form-input"
                :class="{ error: loginErrors.phone }"
                placeholder="请输入手机号"
                @blur="validateLoginField('phone')"
              />
              <div v-if="loginErrors.phone" class="error-message">
                {{ loginErrors.phone }}
              </div>
            </div>
            
            <div class="form-group">
              <label class="form-label">密码</label>
              <input 
                v-model="loginForm.password"
                type="password" 
                class="form-input"
                :class="{ error: loginErrors.password }"
                placeholder="请输入密码"
                @blur="validateLoginField('password')"
              />
              <div v-if="loginErrors.password" class="error-message">
                {{ loginErrors.password }}
              </div>
            </div>
            
            <div class="form-options">
              <label class="checkbox-wrapper">
                <input 
                  v-model="loginForm.remember"
                  type="checkbox" 
                  class="checkbox-input"
                />
                <span class="checkbox-label">记住我</span>
              </label>
              <a href="#" class="forgot-link">忘记密码？</a>
            </div>
            
            <button 
              type="submit" 
              class="submit-btn"
              :disabled="isLoginLoading"
            >
              <span v-if="isLoginLoading">登录中...</span>
              <span v-else>登录</span>
            </button>
          </form>
        </div>
        
        <!-- 注册表单 -->
        <div 
          class="form-wrapper" 
          :class="{ active: activeTab === 'register' }"
          v-show="activeTab === 'register'"
        >
          <form @submit.prevent="handleRegister" class="auth-form">
            <div class="form-group">
              <label class="form-label">用户名</label>
              <input 
                v-model="registerForm.name"
                type="text" 
                class="form-input"
                :class="{ error: registerErrors.name }"
                placeholder="请输入用户名"
                @blur="validateRegisterField('name')"
              />
              <div v-if="registerErrors.name" class="error-message">
                {{ registerErrors.name }}
              </div>
            </div>
            
            <div class="form-group">
              <label class="form-label">手机号</label>
              <div class="inline-row">
                <input 
                  v-model="registerForm.phone"
                  type="tel" 
                  class="form-input"
                  :class="{ error: registerErrors.phone }"
                  placeholder="请输入手机号"
                  @blur="validateRegisterField('phone')"
                />
                <button 
                  type="button"
                  class="code-btn"
                  :disabled="countdown > 0 || isSendingCode"
                  @click="handleSendCode"
                >
                  <span v-if="countdown > 0">{{ countdown }}s</span>
                  <span v-else>获取验证码</span>
                </button>
              </div>
              <div v-if="registerErrors.phone" class="error-message">
                {{ registerErrors.phone }}
              </div>
            </div>
            
            <div class="form-group">
              <label class="form-label">密码</label>
              <input 
                v-model="registerForm.password"
                type="password" 
                class="form-input"
                :class="{ error: registerErrors.password }"
                placeholder="请输入密码"
                @blur="validateRegisterField('password')"
              />
              <div v-if="registerErrors.password" class="error-message">
                {{ registerErrors.password }}
              </div>
            </div>
            
            <!-- 确认密码 -->
            <div class="form-group">
              <label class="form-label">确认密码</label>
              <input 
                v-model="registerForm.confirmPassword"
                type="password" 
                class="form-input"
                :class="{ error: registerErrors.confirmPassword }"
                placeholder="请再次输入密码"
                @blur="validateRegisterField('confirmPassword')"
              />
              <div v-if="registerErrors.confirmPassword" class="error-message">
                {{ registerErrors.confirmPassword }}
              </div>
            </div>
            
            <div class="form-group">
              <label class="form-label">验证码</label>
              <input 
                v-model="registerForm.code"
                type="text" 
                class="form-input"
                placeholder="请输入短信验证码"
              />
            </div>
            
            <button 
              type="submit" 
              class="submit-btn"
              :disabled="isRegisterLoading"
            >
              <span v-if="isRegisterLoading">注册中...</span>
              <span v-else>注册</span>
            </button>
          </form>
        </div>
      </div>
      
      <!-- 底部链接 -->
      <div class="auth-footer">
        <p class="footer-text">
          登录即表示您同意我们的
          <a href="#" class="footer-link">服务条款</a>
          和
          <a href="#" class="footer-link">隐私政策</a>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 当前激活的标签
const activeTab = ref('login')

// 登录表单数据
const loginForm = reactive({
  phone: '', // 改为phone字段
  password: '',
  remember: false
})

// 注册表单数据
const registerForm = reactive({
  name: '',
  phone: '',
  password: '',
  confirmPassword: '',
  code: ''
})

// 表单错误信息
const loginErrors = reactive({
  phone: '', // 改为phone字段
  password: ''
})

const registerErrors = reactive({
  name: '',
  phone: '',
  password: '',
  confirmPassword: ''
})

// 加载状态
const isLoginLoading = ref(false)
const isRegisterLoading = ref(false)
const isSendingCode = ref(false)
const countdown = ref(0)
let timerId = null

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab
  // 清除错误信息
  clearErrors()
}

// 清除错误信息
const clearErrors = () => {
  Object.keys(loginErrors).forEach(key => {
    loginErrors[key] = ''
  })
  Object.keys(registerErrors).forEach(key => {
    registerErrors[key] = ''
  })
}

// 验证登录字段
const validateLoginField = (field) => {
  const value = loginForm[field]
  
  if (!value.trim()) {
    loginErrors[field] = `${field === 'phone' ? '手机号' : '密码'}不能为空`
    return false
  }
  
  if (field === 'phone') {
    // 检查是否为手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(value)) {
      loginErrors[field] = '请输入有效的手机号'
      return false
    }
  }
  
  if (field === 'password' && value.length < 6) {
    loginErrors[field] = '密码长度不能少于6位'
    return false
  }
  
  loginErrors[field] = ''
  return true
}

// 验证注册字段
const validateRegisterField = (field) => {
  const value = registerForm[field]
  
  if (!value.trim()) {
    registerErrors[field] = `${field === 'name' ? '用户名' : field === 'phone' ? '手机号' : '密码'}不能为空`
    return false
  }
  
  if (field === 'name' && value.length < 2) {
    registerErrors[field] = '用户名长度不能少于2位'
    return false
  }
  
  if (field === 'phone') {
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(value)) {
      registerErrors[field] = '请输入有效的手机号'
      return false
    }
  }
  
  if (field === 'password' && value.length < 6) {
    registerErrors[field] = '密码长度不能少于6位'
    return false
  }
  
  if (field === 'confirmPassword') {
    if (value !== registerForm.password) {
      registerErrors[field] = '两次输入的密码不一致'
      return false
    }
  }
  
  registerErrors[field] = ''
  return true
}

// 验证整个登录表单
const validateLoginForm = () => {
  const isPhoneValid = validateLoginField('phone')
  const isPasswordValid = validateLoginField('password')
  return isPhoneValid && isPasswordValid
}

// 验证整个注册表单
const validateRegisterForm = () => {
  const isNameValid = validateRegisterField('name')
  const isPhoneValid = validateRegisterField('phone')
  const isPasswordValid = validateRegisterField('password')
  const isConfirmPasswordValid = validateRegisterField('confirmPassword')
  return isNameValid && isPhoneValid && isPasswordValid && isConfirmPasswordValid
}

// 发送验证码
const handleSendCode = async () => {
  // 校验手机号
  if (!validateRegisterField('phone')) return
  if (countdown.value > 0 || isSendingCode.value) return
  
  try {
    isSendingCode.value = true
    const { sendCode } = await import('@/api/auth')
    const code = await sendCode(registerForm.phone)
    // 后端当前直接返回验证码用于演示；生产环境应通过短信下发
    console.log('短信验证码:', code)
    // 便于联调：自动填充到输入框，并提示包含验证码
    if (code) registerForm.code = String(code)
    ElMessage.success(`验证码已发送：${code}`)
    // 开始60秒倒计时
    countdown.value = 60
    timerId = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timerId)
        timerId = null
      }
    }, 1000)
  } catch (error) {
    ElMessage.error(error.message || '发送验证码失败')
  } finally {
    isSendingCode.value = false
  }
}

// 处理登录
const handleLogin = async () => {
  if (!validateLoginForm()) {
    return
  }
  
  isLoginLoading.value = true
  
  try {
    // 使用状态管理进行登录
    await userStore.userLogin({
      phone: loginForm.phone,
      password: loginForm.password
    })
    
    ElMessage.success('登录成功！')
    
    // 跳转到首页
    router.push('/home')
  } catch (error) {
    ElMessage.error(error.message || '登录失败，请重试')
  } finally {
    isLoginLoading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  if (!validateRegisterForm()) {
    return
  }
  
  isRegisterLoading.value = true
  
  try {
    // 使用状态管理进行注册
    await userStore.userRegister({
      name: registerForm.name,
      phone: registerForm.phone,
      password: registerForm.password,
      code: registerForm.code
    })

    ElMessage.success('注册成功，正在进入首页...')
    
    // 跳转到首页
    router.push('/home')

    // 清空注册表单
    Object.keys(registerForm).forEach(key => {
      registerForm[key] = ''
    })
    countdown.value = 0
    if (timerId) clearInterval(timerId)
  } catch (error) {
    ElMessage.error(error.message || '注册失败，请重试')
  } finally {
    isRegisterLoading.value = false
  }
}
</script>

<style scoped>
.auth-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #f0f8ff 0%, #f5f5f5 30%, #f5f5f5 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  /* 允许页面在内容较多时滚动，避免按钮被遮挡 */
  overflow-y: auto;
}

.auth-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
}

.bg-decoration {
  position: absolute;
  top: -50%;
  right: -20%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(102, 126, 234, 0.1) 0%, transparent 70%);
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(5deg); }
}

.auth-container {
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
  position: relative;
  z-index: 1;
  backdrop-filter: blur(10px);
  /* 小屏时容器内部也可滚动，避免内容被裁切 */
  max-height: calc(100vh - 40px);
  overflow-y: auto;
}

.auth-header {
  text-align: center;
  margin-bottom: 30px;
}

.auth-title {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin: 0 0 8px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.auth-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.auth-tabs {
  display: flex;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 4px;
  margin-bottom: 30px;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  color: #666;
}

.tab-item.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.form-container {
  position: relative;
}

.form-wrapper {
  opacity: 0;
  transform: translateX(20px);
  transition: all 0.3s ease;
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
}

.form-wrapper.active {
  opacity: 1;
  transform: translateX(0);
  position: relative;
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.inline-row {
  display: flex;
  gap: 10px;
}

.code-btn {
  white-space: nowrap;
  padding: 12px 14px;
  border: none;
  border-radius: 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
  cursor: pointer;
}

.code-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.form-input {
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 10px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: #fafbfc;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-input.error {
  border-color: #ff4757;
  background: #fff5f5;
}

.error-message {
  color: #ff4757;
  font-size: 12px;
  margin-top: 4px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.checkbox-input {
  margin-right: 8px;
  width: 16px;
  height: 16px;
  accent-color: #667eea;
}

.checkbox-label {
  font-size: 14px;
  color: #666;
}

.forgot-link {
  font-size: 14px;
  color: #667eea;
  text-decoration: none;
  transition: color 0.3s ease;
}

.forgot-link:hover {
  color: #764ba2;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 14px 20px;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 10px;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.auth-footer {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e1e5e9;
}

.footer-text {
  font-size: 12px;
  color: #999;
  margin: 0;
  line-height: 1.5;
}

.footer-link {
  color: #667eea;
  text-decoration: none;
  transition: color 0.3s ease;
}

.footer-link:hover {
  color: #764ba2;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .auth-page {
    padding: 16px;
  }
  
  .auth-container {
    padding: 30px 24px;
    border-radius: 16px;
  }
  
  .auth-title {
    font-size: 24px;
  }
  
  .auth-subtitle {
    font-size: 13px;
  }
  
  .tab-item {
    padding: 10px 16px;
    font-size: 14px;
  }
  
  .form-input {
    padding: 10px 14px;
    font-size: 15px;
  }
  
  .submit-btn {
    padding: 12px 18px;
    font-size: 15px;
  }
}

@media (max-width: 480px) {
  .auth-container {
    padding: 24px 20px;
  }
  
  .auth-title {
    font-size: 22px;
  }
  
  .tab-item {
    padding: 8px 12px;
    font-size: 13px;
  }
}
</style>
